/*
 * autor: Marcin Formela
*/


package pl.formit04.mail;


import com.google.appengine.api.datastore.Key;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import java.util.List;
import javax.jdo.Query;

@PersistenceCapable
public class IdStore
{
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private String seqName;
    
    @Persistent
    private int seqNumber;

    public static int getSeqNumber(PersistenceManager pm, String name) 
    {
    	Query query = pm.newQuery(IdStore.class);
    	query.setFilter("seqName == :seqNameParam");
    	IdStore id = null;
    	try {
            List<IdStore> results = (List<IdStore>) query.execute(name);
            id = results.get(0);
            
            if(name.equals("user"))
            {	
            	Query queryUser = pm.newQuery(EmailStore.class);
            	List<IdStore> resultsUser = (List<IdStore>) queryUser.execute();
            	int temp = 0;
            	if((id.seqNumber + 1) > resultsUser.size())
            	{
            		temp = id.seqNumber;
            	}
            	else
            	{
            		temp = id.seqNumber + 1;
            	}
//            	System.out.println(temp);
//            	System.out.println(id.seqNumber);
//            	System.out.println(resultsUser.size());
            	if(temp >= resultsUser.size())
            	{
            		
            		id.seqNumber = temp - resultsUser.size();
            	}
            	else
            	{
            		id.seqNumber = temp;
            	}
//            	System.out.println(id.seqNumber);
            }
            else
            {
            	id.seqNumber++;
            }
            pm.makePersistent(id);
            pm.flush();
            
        } 
    	finally 
        {
            query.closeAll();
        }
//    	System.out.println("get id:" + id.seqNumber);
    	return id.seqNumber; 
    }
    
    public int getSeqNumberNoIncrease() {
		return seqNumber;
	}

	public IdStore(String seqName, int seqNumber) 
    {
        this.seqName = seqName;
    	this.seqNumber = seqNumber;
    }

    public Key getKey() {
        return key;
    }
     

	public String getSeqName() 
	{
		return seqName;
	}

}